package org.gbif.agi.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.appfuse.service.GenericManager;
import org.gbif.agi.model.GenusUsage;
import org.appfuse.webapp.action.BaseAction;

import java.util.List;

public class GenusUsageAction extends BaseAction implements Preparable {
    private GenericManager<GenusUsage, Long> genusUsageManager;
    private List genusUsages;
    private GenusUsage genusUsage;
    private Long  id;

    public void setGenusUsageManager(GenericManager<GenusUsage, Long> genusUsageManager) {
        this.genusUsageManager = genusUsageManager;
    }

    public List getGenusUsages() {
        return genusUsages;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String genusUsageId = getRequest().getParameter("genusUsage.id");
            if (genusUsageId != null && !genusUsageId.equals("")) {
                genusUsage = genusUsageManager.get(new Long(genusUsageId));
            }
        }
    }

    public String list() {
        genusUsages = genusUsageManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public GenusUsage getGenusUsage() {
        return genusUsage;
    }

    public void setGenusUsage(GenusUsage genusUsage) {
        this.genusUsage = genusUsage;
    }

    public String delete() {
        genusUsageManager.remove(genusUsage.getId());
        saveMessage(getText("genusUsage.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            genusUsage = genusUsageManager.get(id);
        } else {
            genusUsage = new GenusUsage();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (genusUsage.getId() == null);

        genusUsageManager.save(genusUsage);

        String key = (isNew) ? "genusUsage.added" : "genusUsage.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}